package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.service.useractivity.UserActivityStatsService;
import cn.iocoder.yudao.module.system.service.userbehavior.UserBehaviorStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户统计数据完整性检查定时任务
 *
 * @author 系统开发团队
 */
@Component
@Slf4j
public class UserStatsIntegrityCheckJob implements JobHandler {

    @Resource
    private UserActivityStatsService userActivityStatsService;

    @Resource
    private UserBehaviorStatsService userBehaviorStatsService;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        log.info("[execute] 开始执行用户统计数据完整性检查定时任务");

        try {
            List<String> issues = new ArrayList<>();
            
            // 检查最近7天的数据完整性
            LocalDate endDate = LocalDate.now().minusDays(1);
            LocalDate startDate = endDate.minusDays(6);

            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                // 检查用户活动统计数据完整性
                Map<String, Object> activityIntegrityResult = userActivityStatsService.checkDataIntegrity(date, date);
                Boolean activityIntegrity = (Boolean) activityIntegrityResult.get("isHealthy");
                if (activityIntegrity == null || !activityIntegrity) {
                    String issue = String.format("用户活动统计数据不完整，日期：%s", date);
                    issues.add(issue);
                    log.warn("[execute] {}", issue);
                    
                    // 尝试重新计算
                    try {
                        boolean recalcResult = userActivityStatsService.recalculateUserActivityStats(date);
                        if (recalcResult) {
                            log.info("[execute] 重新计算用户活动统计成功，日期：{}", date);
                        } else {
                            log.error("[execute] 重新计算用户活动统计失败，日期：{}", date);
                        }
                    } catch (Exception e) {
                        log.error("[execute] 重新计算用户活动统计异常，日期：{}", date, e);
                    }
                }

                // 检查用户行为统计数据完整性
                Map<String, Object> behaviorIntegrityResult = userBehaviorStatsService.checkDataIntegrity(date, date);
                // 对于用户行为统计，检查integrityRate是否为100%
                Double integrityRate = (Double) behaviorIntegrityResult.get("integrityRate");
                if (integrityRate == null || integrityRate < 100.0) {
                    String issue = String.format("用户行为统计数据不完整，日期：%s，完整性：%.2f%%", date, integrityRate != null ? integrityRate : 0.0);
                    issues.add(issue);
                    log.warn("[execute] {}", issue);
                    
                    // 尝试重新计算
                    try {
                        boolean recalcResult = userBehaviorStatsService.recalculateUserBehaviorStats(date);
                        if (recalcResult) {
                            log.info("[execute] 重新计算用户行为统计成功，日期：{}", date);
                        } else {
                            log.error("[execute] 重新计算用户行为统计失败，日期：{}", date);
                        }
                    } catch (Exception e) {
                        log.error("[execute] 重新计算用户行为统计异常，日期：{}", date, e);
                    }
                }
            }

            // 检查计算进度
            Map<String, Object> activityProgressMap = userActivityStatsService.getCalculationProgress(startDate, endDate);
            Map<String, Object> behaviorProgressMap = userBehaviorStatsService.getCalculationProgress(startDate, endDate);
            
            String activityProgress = String.format("完成率：%.2f%%", (Double) activityProgressMap.getOrDefault("progressRate", 0.0));
            String behaviorProgress = String.format("完成率：%.2f%%", (Double) behaviorProgressMap.getOrDefault("completionRate", 0.0));
            
            log.info("[execute] 用户活动统计计算进度：{}", activityProgress);
            log.info("[execute] 用户行为统计计算进度：{}", behaviorProgress);

            // 返回执行结果
            String result;
            if (issues.isEmpty()) {
                result = String.format("数据完整性检查通过，检查日期范围：%s 至 %s，活动统计进度：%s，行为统计进度：%s",
                        startDate, endDate, activityProgress, behaviorProgress);
            } else {
                result = String.format("发现 %d 个数据完整性问题：%s，检查日期范围：%s 至 %s",
                        issues.size(), String.join("; ", issues), startDate, endDate);
            }

            log.info("[execute] 完成执行用户统计数据完整性检查定时任务，结果：{}", result);
            return result;

        } catch (Exception e) {
            log.error("[execute] 执行用户统计数据完整性检查定时任务失败", e);
            throw e;
        }
    }
}